package cn.xiongxf.org.service.impl;

import cn.xiongxf.basic.service.impl.BaseServiceImpl;
import cn.xiongxf.org.domain.Department;
import cn.xiongxf.org.mapper.DepartmentMapper;
import cn.xiongxf.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void add(Department department) {
        departmentMapper.save(department);
        //System.out.println(department);   查看三种情况下的部门路径数据形式
        // 获取部门路径
        if (department.getParent_id() == null){
            // 1.顶级部门：/id
            department.setDirPath("/"+department.getId());
        }else {
            // 2.非顶级部门：/上级部门路径/id
            Department pd = departmentMapper.loadById(department.getParent_id());
            department.setDirPath(pd.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        // 获取部门路径
        if (department.getParent_id() == null){
            // 1.顶级部门：/id
            department.setDirPath("/"+department.getId());
        }else {
            // 2.非顶级部门：/上级部门路径/id
            Department pd = departmentMapper.loadById(department.getParent_id());
            department.setDirPath(pd.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        Map<Long, Department> map = new HashMap<>();
        for (Department  department:departments) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        for(Department department:departments){
            // 顶级部门
            if (department.getParent_id() == null){
                deptTree.add(department);
            }else{
                // 获取当前部门的父部门
                Long parent_id = department.getParent_id();
                Department parentDepartment = map.get(parent_id);
                // 将自己添加到上级部门的子部门中
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }

}
